<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <!-- card 头部 内容 -->
    <template #header>
      <div>
        <el-button
          type="primary"
          size="default"
          icon="ele-Plus"
          @click="addTrademark"
          >添加</el-button
        >
      </div>
    </template>
    <!-- 表格 -->
    <!--
        stripe  斑马纹表格

        column属性
        label  显示标题
     -->
    <el-table :stripe="true" border :data="records" v-loading="tableLoading">
      <el-table-column type="index" width="80" label="序号" />
      <el-table-column label="品牌名称" prop="tmName" />
      <el-table-column label="品牌logo" v-slot="{ row }">
        <div>
          <img :src="row.logoUrl" alt="" width="150" />
        </div>
      </el-table-column>
      <el-table-column label="操作" v-slot="{ row }">
        <div>
          <el-button
            type="warning"
            size="small"
            icon="ele-Edit"
            @click="updateTrademark(row)"
            >修改</el-button
          >

          <el-popconfirm
            title="您确定要删除此条数据吗?"
            @confirm="deleteTrademark(row.id)"
          >
            <template #reference>
              <el-button type="danger" size="small" icon="ele-Delete"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </div>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->

    <el-pagination
      :style="{ marginTop: '20px' }"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 7, 9]"
      layout="  prev, pager, next,sizes,total"
      :total="total"
    />
    <!-- 品牌添加对话框 -->
    <el-dialog v-model="dialogVisible" width="50%" align-center>
      <template #header>
        <div>
          <h4>{{ `${tmInfo.id ? "修改" : "添加"}` }}品牌</h4>
        </div>
      </template>
      <div>
        <el-form
          label-width="80px"
          :inline="false"
          :model="tmInfo"
          :rules="rules"
          ref="ruleFormRef"
        >
          <el-form-item label="品牌名称" prop="tmName">
            <el-input v-model="tmInfo.tmName"></el-input>
          </el-form-item>
          <el-form-item label="品牌logo" prop="logoUrl">
            <el-upload
              class="avatar-uploader"
              :action="`${baseUrl}/admin/product/upload`"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :show-file-list="false"
            >
              <img v-if="tmInfo.logoUrl" :src="tmInfo.logoUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"
                ><ele-Plus
              /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCommit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Trademark",
});
</script>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue";
import {
  reqGetTrademarkList,
  type TrademarkListType,
  reqAddTrademark,
  type TrademarkItemType,
  reqUpdataTrademark,
  reqDeleteTrademark,
} from "@/api/product";
import { ElMessage, type FormRules, type UploadProps } from "element-plus";
// 当前页
const currentPage = ref(1);
// 每页展示条数
const pageSize = ref(3);
// 总条数
const total = ref(0);
// 在表格中用于数据展示
const records = ref<TrademarkListType>([]);
// 是否时loading 状态
const tableLoading = ref(false);

// 初始化获取数据
onMounted(() => {
  getTrademarkInfo();
});

// 发送请求获取商品列表的方法
const getTrademarkInfo = async () => {
  // 进入loading 状态
  tableLoading.value = true;
  const re = await reqGetTrademarkList(currentPage.value, pageSize.value);
  //   console.log(re);
  // 保存品牌数据
  records.value = re.records;
  //   修改总条数
  total.value = re.total;
  //   取消loading状态
  tableLoading.value = false;
};

// 当页码发生改变时重新发送请求展示页面
watch([currentPage, pageSize], () => {
  getTrademarkInfo();
});

// 品牌对话框

// 是否展示品牌对话框
const dialogVisible = ref(false);

// logo 图片
// const imageUrl = ref("");
// 品牌名称
// const tmName = ref("");

// 品牌信息
const tmInfo = ref(<TrademarkItemType>{
  tmName: "",
  logoUrl: "",
});

// tmName 品牌名称自定义规则
const checkTmName = (rule: any, value: any, callback: any) => {
  // if (value.length <= 5 && value.length >= 2) return true;
  // else return false

  return value.length <= 5 && value.length >= 2;
};

// 表单校验规则
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "品牌名称不能为空", trigger: "blur" },
    { validator: checkTmName, message: "品牌名称长度2-5", trigger: "blur" },
  ],
  logoUrl: [{ required: true, message: "品牌logo不能为空", trigger: "blur" }],
});

// 当前开发环境api
const baseUrl = import.meta.env.VITE_API_URL;

// 品牌信息更新提交表单元素
const ruleFormRef = ref();

// 点击添加按钮事件
const addTrademark = async () => {
  // 清除表单验证残留
  await ruleFormRef.value?.clearValidate();
  dialogVisible.value = true;
  //   打开时清除数据
  tmInfo.value = {
    tmName: "",
    logoUrl: "",
  };
};

// 品牌logo上传成功时触发的方法
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  tmInfo.value.logoUrl = response.data;
};

// 品牌logo上传前时触发的logo
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

// 点击确认按钮时触发的事件
const confirmCommit = async () => {
  try {
    // 表单整体校验
    await ruleFormRef.value.validate();

    // 判断是否有id  如果有则是数据回填修改，没有则是新增
    if (tmInfo.value.id) {
      //   发送修改请求
      await reqUpdataTrademark(tmInfo.value);
      //   成功添加提示
      ElMessage.success("修改品牌成功！");
    } else {
      //   发送新增品牌请求
      await reqAddTrademark(tmInfo.value);
      //   成功添加提示
      ElMessage.success("新增品牌成功！");
    }

    //   关闭添加对话框
    dialogVisible.value = false;

    //   重新发送请求新数据
    getTrademarkInfo();
  } catch (e) {
    ElMessage.error("您输入的内容不符合规则！");
    return;
  }
};

// 点击修改按钮事件
const updateTrademark = async (row: TrademarkItemType) => {
  // 清除表单验证残留
  await ruleFormRef.value?.clearValidate();

  // 打开对话框
  dialogVisible.value = true;
  // 显示要回填的数据
  tmInfo.value = { ...row };
};

//  点击删除按钮事件
const deleteTrademark = async (id: number) => {
  // 发送删除请求
  await reqDeleteTrademark(id);
  // 删除成功提示
  ElMessage.success("删除成功！");
  // 重新请求数据
  getTrademarkInfo();
};
</script>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
